package com.fas.system.service.impl;

import com.fas.common.core.domain.AjaxResult;
import com.fas.common.core.redis.RedisCache;
import com.fas.common.utils.DictUtils;
import com.fas.system.domain.FasInspectionRecord;
import com.fas.system.domain.FasInspectionRecordData;
import com.fas.system.domain.FasInspectionTask;
import com.fas.system.domain.FasWordOrder;
import com.fas.system.domain.vo.*;
import com.fas.system.mapper.*;
import com.fas.system.service.IFasInspectionRecordService;
import com.fas.system.service.IFasWordOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class FasInspectionRecordServiceImpl implements IFasInspectionRecordService {

    @Resource
    private FasInspectionRecordMapper fasInspectionRecordMapper;
    @Resource
    private FasInspectionRecordDataMapper fasInspectionRecordDataMapper;
    @Resource
    private IFasWordOrderService fasWordOrderService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private FasInspectionLineMapper fasInspectionLineMapper;
    @Resource
    private FasInspectionTaskMapper fasInspectionTaskMapper;
    @Resource
    private FasWordOrderEngineerMapper fasWordOrderEngineerMapper;
    @Resource
    private FasInspectionTaskServiceImpl fasInspectionTaskServiceImpl;

    /**
     * 巡检路线设施数据提交
     *
     * @param fasInspectionRecord
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult submit(FasInspectionRecord fasInspectionRecord) {
        // 判断这条记录是否被提交
        int existsNum = fasInspectionRecordMapper.existsRecord(fasInspectionRecord);
        if (existsNum > 0) {//数据库中已存在数据，重复提交
            return AjaxResult.error("该记录已提交，请勿重复提交！");
        }
        // 如果巡检员上报方式是上报工单，在工单表添加数据         处理方式（0：现场处理，1：上报工单, 2 ：维保单位自己处理）
        if (fasInspectionRecord.getTreatmentMethod() == 1 ) {
            FasWordOrder fasWordOrder = new FasWordOrder();
            fasWordOrderService.insertNullData(fasWordOrder);
            Integer wordOrderId = fasWordOrder.getId();//工单id
            fasInspectionRecord.setWordOrderId(wordOrderId);
            // 给微信小程序的维保单位推送工单信息
//            String msg = String.format("工单消息：%s 工单编号：%s,请及时处理。","\n",id);
//            PushData<String> listPushData = new PushData<>(Constants.WORD_ORDER, msg);
//            listPushData.setUserList(pushService.getManUserList());
//            pushService.sendMsg(listPushData);//巡检员提交工单，给维保单位推送工单消息
        }

        // 提交设施记录
        int result = fasInspectionRecordMapper.submit(fasInspectionRecord);

        List<FasInspectionRecordData> recordDataList = fasInspectionRecord.getRecordDataList();
        if (result > 0 && !CollectionUtils.isEmpty(recordDataList)) {// 保存设施的数据项数据
            recordDataList.forEach(r -> {
                r.setFacilityId(fasInspectionRecord.getFacilityId());
                r.setFasInspectionRecordId(fasInspectionRecord.getId());
            });
            fasInspectionRecordDataMapper.batchInsertData(recordDataList);
        }
        //判断这条设施数据是否是这个任务的最后一条数据，是的话更新fas_inspection_task表状态
        this.judgeFacilityLastData(fasInspectionRecord.getFasInspectionTaskId());
        return AjaxResult.success();
    }

    @Override
    public FasInspectionRecord findByFacilityAndTaskId(FasInspectionRecord fasInspectionRecord) {
        return fasInspectionRecordMapper.findByFacilityAndTaskId(fasInspectionRecord);
    }

    @Override
    public List<InspectionRecodeVo> findAllRecord(InspectionRecodeVo inspectionRecodeVo) {
        List<InspectionRecodeVo> list = fasInspectionRecordMapper.findAllRecord(inspectionRecodeVo);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public List<MissedInspectionVo> missedInspection(MissedInspectionVo missedInspectionVo) {
        return fasInspectionRecordMapper.missedInspection(missedInspectionVo);
    }

    @Override
    public List<FacilityRecordVo> findFacilityOrderPage(FacilityRecordVo facilityRecordVo) {
        List<FacilityRecordVo> list = fasInspectionRecordMapper.findFacilityOrderPage(facilityRecordVo);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public FacilityRecordDetailVo findAuditDetails(Integer id) {
        FacilityRecordDetailVo details = fasInspectionRecordMapper.findAuditDetails(id);
        if (details != null) {
            details.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(details.getCooperationCompanyId()));
            if (details.getEngineerResult() != null && details.getEngineerResult() == 2) {
                details.setEngineerList(fasWordOrderEngineerMapper.findByWordOrderId(details.getId()));
            }
        }
        return details;
    }

    @Override
    public List<EquipmentWordVo> findDeviceOrderPage(EquipmentWordVo equipmentWordVo) {
        List<EquipmentWordVo> list = fasInspectionRecordMapper.findDeviceOrderPage(equipmentWordVo);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public EquipmentWordVo findEquipmentDetails(Integer id) {
        EquipmentWordVo equipmentDetails = fasInspectionRecordMapper.findEquipmentDetails(id);
        if (equipmentDetails != null) {
            if(equipmentDetails.getEngineerResult() != null && equipmentDetails.getEngineerResult() == 2){
                equipmentDetails.setEngineerList(fasWordOrderEngineerMapper.findByWordOrderId(equipmentDetails.getId()));
            }
            equipmentDetails.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(equipmentDetails.getCooperationCompanyId()));
            equipmentDetails.setSystemName(DictUtils.getDictLabel("sys_equipment_system",equipmentDetails.getSystemId()));
        }
        return equipmentDetails;
    }

    @Override
    public TrendChangeStatistics trendChange(Integer deptId) {
        Date today = new Date();//获取今天的日期
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        c.add(Calendar.DAY_OF_MONTH, -6);
        List<String> dateList = fasInspectionTaskServiceImpl.getBetweenDate(c.getTime(),new Date());
        List<Integer> checked = new ArrayList<>(); //已检查
        List<Integer> notChecked = new ArrayList<>();//未检查
        List<String> dateTime = new ArrayList<>();// 时间列表

        for (String time : dateList) {
            List<FasInspectionTask> byInspectionDate = fasInspectionTaskMapper.findByInspectionDate(time);
            int completeNum = byInspectionDate.stream().mapToInt(FasInspectionTask::getLineCompleteNum).sum();
            int totalNum = byInspectionDate.stream().mapToInt(FasInspectionTask::getTaskNum).sum();
            int unCheckNum = totalNum-completeNum;
            checked.add(completeNum);
            notChecked.add(unCheckNum);
            dateTime.add(time);
        }
        return new TrendChangeStatistics(checked,notChecked,dateTime);
    }

    private void judgeFacilityLastData(Long taskId) {
        // 故障扫码或者手动填报的数据不是路线上的设施，直接跳过
        if (taskId == null) return;
        List<IpqcLineBuilding> ipqcInspectionLines = fasInspectionLineMapper.miniappIpqcLineBuilding(taskId);
        Integer status = null;  // 巡检路线状态（0：已完成，1：进行中，2：待开始）
        int facilityCompleteNum = 0;
        for (IpqcLineBuilding ipqcInspectionLine : ipqcInspectionLines) {
            facilityCompleteNum += ipqcInspectionLine.getFacilityCompleteStatus();
        }
        if (facilityCompleteNum == ipqcInspectionLines.size()) {//该建筑下设施全部巡检完成
            status = 0;
        } else if (0 < facilityCompleteNum && facilityCompleteNum < ipqcInspectionLines.size()) {//该建筑下还有为检设施，进行中
            status = 1;
        } else if (facilityCompleteNum == 0) { //该建筑下的设施一个都没开始检查
            status = 2;
        }
        fasInspectionTaskMapper.miniappTaskStatus(taskId,status);
    }
}
